package com.xayq.orap.oauth.controller;

import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xayq.orap.oauth.MyOAuthTokenRequest;
import com.xayq.orap.oauth.token.OAuthTokenHandleDispatcher;
import com.xayq.orap.utils.CommonUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
public class OAuthTokenController {

	@Autowired
    private OAuthTokenHandleDispatcher oAuthTokenHandleDispatcher;
    /**
     * Handle grant_types as follows:
     * <p/>
     * grant_type=authorization_code
     * grant_type=password
     * grant_type=refresh_token
     * grant_type=client_credentials
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    @RequestMapping("/token")
    public void authorize(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            MyOAuthTokenRequest tokenRequest = new MyOAuthTokenRequest(request);

            //OAuthTokenHandleDispatcher tokenHandleDispatcher = new OAuthTokenHandleDispatcher(tokenRequest, response);
            oAuthTokenHandleDispatcher.dispatch(tokenRequest, response);

        } catch (OAuthProblemException e) {
            //exception
            OAuthResponse oAuthResponse = OAuthASResponse
                    .errorResponse(HttpServletResponse.SC_FOUND)
                    .location(e.getRedirectUri())
                    .error(e)
                    .buildJSONMessage();
            CommonUtils.writeOAuthJsonResponse(response, oAuthResponse);
        }

    }
}
